import { useState, useEffect } from 'react'
import { Form, Select, Input, message, Cascader } from 'antd';
import CommonModal from '@/components/CommonModal'
import CommonLoading from '@/components/CommonLoading';
import { layout4 } from '@/utils/config'
import { getSfPruductListOp, saveSfOp, getSfDetailSfOp, updateSfOp } from '../service';
import { getAllArea } from '@/services/common';

const { Option } = Select

const { TextArea } = Input
//新增顺丰面单授权弹窗

let areaList = [];

 const AddSFModal = ({ visible, handleOk, handleCancel }) => {
  const [form] = Form.useForm();

  const [loading, setLoading] = useState(false);//loading
  const [query, setQuery] = useState({});//详情数据回填表单
  const [details, setDetails] = useState('')

  const [productList, setList] = useState([])

  useEffect(()=>{
    getAreaList();
  },[])

   useEffect(()=>{
     if(visible){
       if(visible != 'add'){
        getDetailsInfo()
       }
       if(!productList.length){
        getSfPruductList()
       }
     }else{
      form.resetFields();
     }
   },[visible])

   useEffect(()=>{
    form.resetFields();
  },[query])

    // 获取顺丰时效产品
    const getSfPruductList = async () => {
      setLoading(true) 
      const { success, data = [] } = await getSfPruductListOp();
      if (success && data) {
        setList(data)
      }
      setLoading(false)
   }

     // 获取地区列表
  const getAreaList = async () => { 
    const { success, data = [] } = await getAllArea();
    if (success) {
      areaList = data
    }
  }

  // 获取详情
  const getDetailsInfo = async () => {
    setLoading(true);
    const { success, data = {} } = await getSfDetailSfOp({id:visible});
    if (success) {
      const { extend, province, city, area } = data;
      const obj = JSON.parse(extend);//扩展字段解析对象
      const newQuery = {
        ...data,
        ...obj,
        customerCode: obj.monthlyCard,
        expressTypeId: obj.expressTypeId ? Number(obj.expressTypeId) : undefined,
        extend:undefined
      }
      if(province || city || area){
        newQuery.cascaderAddress = [province, city, area];
      }
      setQuery(newQuery)
    }
    setLoading(false);
 }

  const onOk = () => {
    form.validateFields().then( async val=>{
      if(val.cascaderAddress){
        const [province, city, area] = val.cascaderAddress;
        val = {
          province,
          city,
          area,
          ...val,
          cascaderAddress:undefined
        }
      }
      setLoading(true);
      let res;
      if(visible == 'add'){//新增
       res = await saveSfOp(val)
      }else{
        res = await updateSfOp({//更新
          ...val,
          id:visible,
        })
      }
     const { success, msg } = res
      if(success){
        message.success(msg);
        handleOk();
        onCancel();
      }
      setLoading(false);
    })
  }

  const onCancel = () => {
    handleCancel();
    setQuery({});
    setDetails('');
  }

  return (
    <CommonModal
       title='顺丰面单授权'
       visible={visible}
       onOk={onOk}
       onCancel={onCancel}
    >
      <Form form={form} name='add-sf-auth-form' {...layout4} initialValues={{ ...query }}>

        <Form.Item  name="customerCode" label="月结账号" rules={[{ required: true, message: '月结账号不能为空' }]}>
          <Input placeholder="请输入签约编码"  />
        </Form.Item>

        <Form.Item  name="partnerId" label="顾客编码" rules={[{ required: true, message: '顾客编码不能为空' }, { pattern:/^[^\u4e00-\u9fa5]+$/, message:"不允许输入中文"}]}>
          <Input placeholder="请输入顾客编码" />
        </Form.Item>

        <Form.Item  name="checkWord" label="校验码" rules={[{ required: true, message: '校验码不能为空' }, { pattern:/^[^\u4e00-\u9fa5]+$/, message:"不允许输入中文"}]}>
          <Input placeholder="请输入校验码" maxLength={32} />
        </Form.Item>

        <Form.Item
           label="业务类型"
           name="expressTypeId"
           rules={[{ required: true, message: '请选择时效产品' }]}
         >
           <Select
             showSearch
             placeholder="请选择时效产品"
             optionFilterProp='children'
             allowClear={true}
           >
             {productList.map(d => <Option key={d.typeId} value={d.typeId}>{d.remark}</Option>)}
           </Select>
         </Form.Item>

        <Form.Item name="networkName" label='网点名称' rules={[{ required: true, message: '网点名称不能为空' }]}>
          <Input placeholder="请输入，建议与顺丰合作的网点保持一致" maxLength={20}  />
        </Form.Item>

        <Form.Item  name="senderName" label="发件人" >
          <Input placeholder="请输入寄件人，最多20个字符" maxLength={20} />
        </Form.Item>

        <Form.Item  name="senderMobile" label="联系电话" rules={[{ pattern:/^[\d-]*$/, message: '仅限输入数字和“-”' }]}>
          <Input placeholder="请输入联系电话" />
        </Form.Item>

        <Form.Item name="cascaderAddress" label="发货地区" >
          <Cascader options={areaList} fieldNames={{ label: 'name', value: 'name', children: 'childs' }} placeholder="请选择地区" />
        </Form.Item>

        <Form.Item name="detail" label="详细地址" >
          <TextArea rows={2} maxLength={50} placeholder="请输入详细地址，最多50个字符"  value={details} onChange={(e)=>setDetails(e.target.value.slice(0,50))}/>
        </Form.Item>

      </Form>
      <CommonLoading loading={loading} />
    </CommonModal>
  )
}

export default AddSFModal